package team.chuangshu.lm.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import team.chuangshu.lm.base.ResultUtil;
import team.chuangshu.lm.base.dto.ResultDTO;
import team.chuangshu.lm.controller.UserController;
import team.chuangshu.lm.dto.UserDTO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther zhang
 * @ TO DO
 * @creatTime 2019/5/9 21:15
 **/
@Component
@Slf4j
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private  UserController userController;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        log.info("登录成功!");

        UserDetails user = (UserDetails) authentication.getPrincipal();
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        ResultDTO<Object> userDTO = new ResultDTO<>();
        try {
            log.info(user.getUsername());
            userDTO =  userController.getUserDTO(user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.fromObject(ResultUtil.Success(userDTO));
        log.info(jsonObject.toString());
        response.getWriter().write(jsonObject.toString());

        //response.getWriter().write(objectMapper.writeValueAsString(authentication));

    }
}